package com.zking.controller;

import com.zking.entity.Users;
import com.zking.service.UsersService;
import com.zking.util.EmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("users")
public class UsersController {
    @Autowired
    UsersService usersService;

    @RequestMapping("check")
    @ResponseBody
    public boolean check(String username){
        return usersService.checkUsername(username);
    }

    @RequestMapping("add")
    public String add(Users u, RedirectAttributes ra){
        u.setName(u.getUsername());
        u.setAuthority(1);
        boolean b = usersService.insert(u);
        ra.addFlashAttribute("msg",b?"注册成功":"注册失败");
        return "zhuc";
    }

    @RequestMapping("fasong")
    @ResponseBody
    public boolean fasong(String email, HttpSession session){
        // 生成4位数字验证码
        int code = (int)( ((Math.random()*9)+1) * 1000);
        session.setAttribute("code",String.valueOf(code));
        return EmailUtil.fasong(email,code);
    }

    @RequestMapping("bijiao")
    @ResponseBody
    public boolean bijiao(String usercode, HttpSession session){
        String sysCode = (String) session.getAttribute("code");
        return sysCode.equals(usercode);
    }
}
